<template>
  <div class="class-record page-container">
    <div class="page-title">
      {{ $t("adminCourse.courseRecord") }}
    </div>
    <div class="content" v-loading="loading">
      <el-tabs v-model="activeTab" class="course-tabs" @tab-change="handleTabChange">
        <el-tab-pane v-for="tab in tabs" :key="tab.id" :label="tab.text" :name="tab.id">
          <template v-if="courseList && courseList.length">
            <div class="course-list">
              <div v-for="item in courseList" :key="item.id" class="course-card">
                <div class="cover">
                  <img :src="item?.promotionalImages && item.promotionalImages.length > 0
                    ? item.promotionalImages[0]
                    : item.cover || fallbackCover
                    " alt="course" />
                </div>
                <div class="course-info">
                  <div class="title">
                    {{ item.courseName || "--" }}
                  </div>
                  <div class="tags">
                    <span class="tag" v-if="computeCourseTypeLabel(item.courseType).value">
                      {{ computeCourseTypeLabel(item.courseType).value }}
                    </span>
                    <span class="tag info" v-if="computeScheduleTypeLabel(item.scheduleType).value">
                      {{ computeScheduleTypeLabel(item.scheduleType).value }}
                    </span>
                  </div>
                  <div class="detail">
                    <span>{{ $t("adminCourse.applicableAge") }}：</span>
                    <span>{{ $t("courseDetail.ageUnit", { age: item.applicableAge || 0 }) }}</span>
                  </div>
                  <div class="detail">
                    <span>{{ $t("courseDetail.numberAttendees") }}：</span>
                    <span>{{ courseStudents(item) }}</span>
                  </div>
                  <div class="detail">
                    <span>{{ $t("adminCourse.validTime") }}：</span>
                    <span>{{ courseDateRange(item) }}</span>
                  </div>
                  <div class="detail">
                    <span>{{ $t("courseDetail.location") }}：</span>
                    <span>{{ courseAddress(item) }}</span>
                  </div>
                </div>
                <div class="course-extra">
                  <button class="record-btn" type="button" @click="handleRecord(item)">
                    {{ $t("menu.classRecord") }}
                  </button>
                  <div class="progress-text">
                    <span>{{ t("adminCourse.progressCompleted", { percent: courseProgress(item).percent }) }}</span>
                    <div class="progress-count">
                      {{ t("adminCourse.progressCount", {
                        completed: courseProgress(item).completed, total:
                          courseProgress(item).total
                      }) }}
                    </div>
                  </div>
                  <div class="progress-bar">
                    <div class="bar-track">
                      <div class="bar-fill" :style="{ width: `${courseProgress(item).percent}%` }"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="pagination">
              <Pagination :background="true" :total="total" v-model:current-page="pageNum" v-model:page-size="pageSize"
                @pagination-change="handlePaginationChange" />
            </div>
          </template>
          <template v-else>
            <el-empty :description="$t('noDataAvailable')" />
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>


<script setup>
import { GetCourseStudentClassRecordPage } from "~/apis/admin";
import Pagination from "~/components/Pagination/Pagination.vue";
import { formatDateArea } from "~/utils/utils";
import fallbackCover from "~/assets/login.png";

definePageMeta({
  title: "上课记录",
  zh_hk_title: "上課記錄",
  en_title: "Class Record",
  ssr: true,
  isTokenCheck: true,
});

const { $navigate } = useNuxtApp();
const route = useRoute();
const { t } = useI18n();

const { computeCourseTypeLabel, computeScheduleTypeLabel } = useCourseLabel();
const userStore = useStore.userStore();

const loading = ref(false);
const activeTab = ref(1);
const tabs = computed(() => [
  { id: 0, text: t("adminCourse.tabStudying") },
  { id: 1, text: t("adminCourse.tabExpiring") },
  { id: 2, text: t("adminCourse.tabCompleted") },
]);
const courseList = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);

const courseId = computed(() => route.query.courseId || "");
const studentId = computed(() => route.query.studentId || userStore.user?.id || "");

const countCompletedLessons = (records) => {
  if (!Array.isArray(records)) return 0;
  return records.reduce(
    (count, record) => count + (Number(record.signInStatus) === 1 ? 1 : 0),
    0
  );
};

const mapCourseRecordItem = (item) => {
  const courseInfo = item.courseRespVO || {};
  return {
    id: courseInfo.id,
    ...courseInfo,
    courseSchedulesStudentVOS: item.courseSchedulesStudentVOS || [],
    completedClassHours: countCompletedLessons(item.courseSchedulesStudentVOS || []),
  };
};

const fetchCourseList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNo: pageNum.value,
      pageSize: pageSize.value,
      // status: activeTab.value,
      // courseId: courseId.value,
      // studentId: studentId.value,
    };
    const res = await GetCourseStudentClassRecordPage(params);
    if (res.code === 0 && res.data) {
      const list = Array.isArray(res.data.list) ? res.data.list : [];
      courseList.value = list.map(mapCourseRecordItem);
      total.value = Number(res.data.total) || 0;
    } else {
      courseList.value = [];
      total.value = 0;
    }
  } catch (error) {
    courseList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleTabChange = (paneName) => {
  const nextTab = typeof paneName === "number" ? paneName : Number(paneName);
  const normalizedTab = Number.isNaN(nextTab) ? paneName : nextTab;
  if (activeTab.value === normalizedTab) return;
  activeTab.value = normalizedTab;
  pageNum.value = 1;
  fetchCourseList();
};

const handlePaginationChange = (val) => {
  pageNum.value = val.currentPage;
  pageSize.value = val.pageSize;
  fetchCourseList();
};

const courseProgress = (item) => {
  const records = item.courseSchedulesStudentVOS || [];
  const totalHours = Array.isArray(records) ? records.length : 0;
  const completed = countCompletedLessons(records);
  const safeTotal = totalHours || completed;
  const percent =
    safeTotal > 0 ? Math.min(100, Math.round((completed / safeTotal) * 100)) : 0;

  return {
    total: safeTotal || 0,
    completed,
    percent,
  };
};

const courseStudents = (item) => {
  if (item.numberAttendees !== undefined && item.numberAttendees !== null) {
    return t("courseDetail.numberUnit", { count: item.numberAttendees });
  }
  const min = item.minNumberAttendees;
  const max = item.maxNumberAttendees;
  if (min !== undefined && max !== undefined)
    return t("adminCourse.studentRange", { min, max });
  return item.studentName || "--";
};

const courseAddress = (item) => {
  return item.address || item.location || item.classroom || "--";
};

const courseDateRange = (item) => {
  if (!item.courseStartDate || !item.courseEndDate) return "--";
  try {
    return formatDateArea(item.courseStartDate, item.courseEndDate);
  } catch (error) {
    return "--";
  }
};

const handleRecord = (item) => {
  if (item?.id) {
    const studentQuery = studentId.value ? `&studentId=${studentId.value}` : "";
    $navigate(`/admin/courseSystem/classSchedule?courseId=${item.id}${studentQuery}`);
  }
};

onMounted(() => {
  fetchCourseList();
});
</script>

<style scoped lang="less">
.class-record {
  width: 100%;

  .content {
    width: 100%;
    background: #ffffff;
    border-radius: 10px;
    padding: 16px 14px 20px;
    box-sizing: border-box;
    margin-top: 10px;
  }

  .page-title {
    font-size: 20px;
    font-weight: 600;
    color: #1e2021;
    margin-bottom: 18px;
  }

  .course-tabs {
    :deep(.el-tabs__nav-wrap:after) {
      display: none;
    }
  }

  .course-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .course-card {
    display: grid;
    grid-template-columns: 320px 1fr 240px;
    gap: 18px;
    padding: 16px;
    background: #ffffff;
    border-radius: 10px;
    border: 1px solid #f1f3f5;
    box-shadow: 0 10px 30px rgba(17, 24, 39, 0.06);
    align-items: stretch;
  }

  .cover {
    width: 100%;
    height: 222px;
    border-radius: 8px;
    overflow: hidden;
    background: linear-gradient(135deg, #e5e7eb 0%, #f4f5f7 100%);

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
    }
  }

  .course-info {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 6px 0;

    .title {
      font-size: 18px;
      font-weight: 700;
      color: #1f2937;
      line-height: 1.4;
      margin-bottom: 10px;
    }

    .tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 70px;

      .tag {
        padding: 6px 12px;
        border-radius: 14px;
        font-size: 12px;
        font-weight: 600;
        background: #eff6ff;
        color: #2563eb;
        border: 1px solid #dbeafe;
      }

      .tag.info {
        background: #f8f9fa;
        color: #6b7280;
        border-color: #e5e7eb;
      }
    }

    .detail {
      font-family: PingFang HK, PingFang HK;
      font-weight: 400;
      font-size: 12px;
      color: #656C7E;
      line-height: 20px;
      text-align: left;
      font-style: normal;
      text-transform: none;

      span:first-child {}
    }
  }

  .course-extra {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: space-between;
    padding: 6px 0;

    .record-btn {
      padding: 10px 18px;
      background: #FFEEE8;
      color: #EC4613;
      font-weight: 700;
      cursor: pointer;
      transition: all 0.2s ease;
      border: none;

      // &:hover {
      //   background: #f0743f;
      //   color: #fff;
      // }
    }


    .progress-text {
      margin-top: auto;
      font-size: 14px;
      font-weight: 500;
      color: #059769;
      text-align: right;
      display: flex;
    }

    .progress-bar {
      width: 100%;
      margin-top: 8px;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      gap: 6px;

      .bar-track {
        width: 100%;
        height: 3px;
        background: #eef2f4;
        border-radius: 10px;
        overflow: hidden;
      }

      .bar-fill {
        height: 100%;
        background: #59AA84;
        border-radius: 10px;
      }

      .progress-count {
        font-size: 12px;
        color: #6b7280;
      }
    }
  }

  .pagination {
    margin-top: 12px;
    text-align: left;
    display: flex;
    justify-content: flex-start;
  }
}
</style>
